//
//  DBNetworkTool.swift
//  DBCA
//
//  Created by mugua on 2024/6/29.
//

import Foundation
import Alamofire
import ObjectMapper

typealias successCallback = ((_ model: DBBaseModel) -> ())
typealias failedCallback = ((_ error: Error) -> ())

enum HttpRequestType {
    case get
    case post
}

public class DBNetworkTool {
    
    
    static func commonHeaderParameters() -> [String: Any] {
        
        let sessionId: String = UserDefaults.standard.value(forKey: DBSessionIDKey) as? String ?? ""
        
        let mutableParameters: [String: Any] =
        [
            "beens" : "ios",
            "lies" : DBAppVersion,
            "chaff" : DBDeviceInfoTool.getMachineModelName(),
            "grains" : DBDeviceIDFA.getIDFV(),
            "stay" : DBSystemVersion,
            "use" : "apptrore-dnbn",
            "grapevine" : sessionId,
            "fifth" : DBDeviceIDFA.getIDFV(),
            // 印度999， 印尼902，默认902
            "ambulance" : "902",
        ]
        
        return mutableParameters
    }
    
    
    static func request(method: HttpRequestType, urlString: String, params: [String : Any]?, success: @escaping successCallback, failed: failedCallback?) {
        
        let method = method == .get ? HTTPMethod.get : HTTPMethod.post
        
        var parameters:[String: Any] = commonHeaderParameters()
        
        if let params = params {
            for (key, value) in params {
                parameters[key] = value
            }
        }
        
        var urlStr = URL_Main + urlString
        
        if method == .post {
            urlStr = urlWithQueryParameters(baseURL: urlStr, parameters: parameters)
        }
        
        
        AF.request(urlStr, method: method, parameters: method == .get ? parameters : params, requestModifier: { $0.timeoutInterval = 30 }).responseData { response in
            
            switch response.result {
            case .success(let data):
                do {
                    let jsonStr = try JSONSerialization.jsonObject(with: data)
                    if let json = jsonStr as? [String: Any] {
                        DBLog("success：\(json)")
                        let baseModel = DBBaseModel(JSON: json)
                        
                        if let baseModel = baseModel {
                            
                            if baseModel.glared == -2 {
                                
                                let loginVC = DBLoginViewController()
                                let loginNav = DBBaseNavigationController(rootViewController: loginVC)
                                loginNav.modalPresentationStyle = .fullScreen
                                DBNavigator.currentViewController()?.present(loginNav, animated: true)
                            }
                            
                            success(baseModel)
                            
                            if baseModel.glared != 0 && baseModel.glared != -2 {
                                DBToast.show(text: baseModel.suitably)
                            }
                        }
                    }
                } catch {
                    if let failed = failed {
                        failed(NSError(domain: "json catch", code: -1))
                    }  
                }
                
            case .failure(let error):
                DBLog("error：\(error)")
                if let failed = failed {
                    failed(error)
                }
            }
        }
    }
    
    
    static func urlWithQueryParameters(baseURL: String, parameters: [String: Any]) -> String {

        guard var components = URLComponents(string: baseURL) else {
            return ""
        }

        let queryItems: [URLQueryItem] = parameters.compactMap { key, value in
            guard let stringValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
                return nil
            }
            return URLQueryItem(name: key, value: stringValue)
        }

        components.queryItems = queryItems
        return components.url?.absoluteString ?? ""
    }
    
}
